(function () {
    let template = `
<div class="login-container">
<div class="login__container--inner">
    <div class="usn">
        <label for="username">
            用户名:
        </label>
        <input type="text" id="username" v-model="username">
    </div>
    <div class="psw">
        <label for="password">
            &nbsp;密&nbsp;码:&nbsp;
        </label>
        <input type="text" id="password" v-model="password" @keydown.enter='submit'>
    </div>
    <button class="login--inner__loginbtn" @click="submit">点击登入</button>
</div>
</div>
`
    //登入接口
    //http://chst.vip/users/login
    //METHOD: POST
    //param: *username<string> *password<string>

    Vue.component('login-page', {
        template,
        data() {
            return {
                username: "",
                password: ""
            }
        },
        mounted() {
            let i = 1;
            //this指向组件实例
            this.interval = setInterval(() => {
                console.log(++i)
            }, 500)
        },
        beforeDestroy() {
            clearInterval(this.interval)
        },
        methods: {

            //发起登入请求
            async submit() {
                //获取参数
                let body = JSON.stringify({
                    username: this.username,
                    password: this.password
                })

                try {
                    //获取结果
                    let res = await fetch('http://chst.vip/users/login', {
                        method: 'post',
                        headers: {
                            'content-type': 'application/json'
                        },
                        body
                    }).then(response => response.json())

                    //处理请求回来的结果
                    console.log(res)
                    //解构参数
                    let {state, msg, userInfo, token, permission} = res;

                    //判断state的状态,如果是true登入成功,反之失败

                    if (!state) {
                        alert(msg)
                    } else {
                        //将userInfo,buttons,token都存到本地
                        localStorage.setItem('userInfo', JSON.stringify(userInfo))

                        localStorage.setItem('wq-token', token)

                        localStorage.setItem('permission', JSON.stringify(permission))

                        //跳转到列表页
                        //通过子组件传递父组件传参形式,修改父组件data中的isLogin
                        this.$emit('change-login-state', '1')
                    }


                } catch (e) {
                    alert(e.toString())
                }
            }
        }
    })
})()